package com.zdp.netty.chapter7.client;

import com.zdp.netty.chapter7.entity.SubscribeReq;
import com.zdp.netty.chapter7.entity.SubscribeResp;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

/**
 * @Author zhengdp
 * @Description
 */
public class SubReqClientHandler extends ChannelHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        for(int i =0;i<10;i++) {
            ctx.write(buildReq(i));
        }
        ctx.flush();

    }
    private SubscribeReq buildReq(Integer subId) {
        SubscribeReq req = new SubscribeReq();
        req.setSubReqId(subId);
        req.setAddress("福建省福州市阳光城");
        req.setPhoneNumber("15159xxxxxxx");
        req.setProductName("Netty 权威指南");
        req.setUserName("ZhengDP");
        return req;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        SubscribeResp resp = (SubscribeResp) msg;

        System.out.println("Receive server response : [" + resp + " ]");
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
